﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Hanhud.Web.UI;

namespace Hanhud.Web.Masters
{
    public class HANHUDMaster : UserControl
    {
        private Hanhud.Web.UI.SitePage _currentPage = null;

        /// <summary>
        /// Current page
        /// </summary>
        public Hanhud.Web.UI.SitePage CurrentPage
        {
            get { return _currentPage; }
            protected set { _currentPage = value; }
        }

        private HANHUDHeader _header = null;
        /// <summary>
        /// Page header
        /// </summary>
        public HANHUDHeader Header
        {
            get { return _header; }
            protected set { _header = value; }
        }

        private HANHUDFooter _footer = null;
        /// <summary>
        /// Page footer
        /// </summary>
        public HANHUDFooter Footer
        {
            get { return _footer; }
            protected set { _footer = value; }
        }

        private HANHUDNavigator _navigator = null;
        /// <summary>
        /// Page top-navigator
        /// </summary>
        public HANHUDNavigator Navigator
        {
            get { return _navigator; }
            protected set { _navigator = value; }
        }

        public override string ClientID
        {
            get
            {
                return "HANHUDMaster";
                //return base.ClientID;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public HANHUDMaster()
        {
            Header = new HANHUDHeader();
            Navigator = new HANHUDNavigator();
            Footer = new HANHUDFooter();

            this.Init += new EventHandler(HANHUDMaster_Init);
            this.Load += new EventHandler(HANHUDMaster_Load);
            this.Unload += new EventHandler(HANHUDMaster_Unload);
        }

        void HANHUDMaster_Init(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitScript", @"
                    var IEBrowser = navigator.appName.indexOf(""Microsoft"") > -1;
                    function addEvent(obj, evType, fn)
                    {
                        if (obj.addEventListener) {
                            obj.addEventListener(evType, fn, true);
                            return true;
                        } else if (obj.attachEvent) {
                            var r = obj.attachEvent(""on"" + evType, fn);
                            return r;
                        } else {
                            return false;
                        }
                    }", true);

            Page.ClientScript.RegisterClientScriptInclude("JQuery", Page.ResolveUrl("~/Scripts/jquery-1.4.2.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Core", Page.ResolveUrl("~/Scripts/jquery.ui.core.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Widget", Page.ResolveUrl("~/Scripts/jquery.ui.widget.min.js"));
            //Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Position", Page.ResolveUrl("~/Scripts/jquery.ui.position.min.js"));
            //Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Mouse", Page.ResolveUrl("~/Scripts/jquery.ui.mouse.min.js"));
            //Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Resizable", Page.ResolveUrl("~/Scripts/jquery.ui.resizable.min.js"));
            //Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Dialog", Page.ResolveUrl("~/Scripts/jquery.ui.dialog.min.js"));
        }

        void HANHUDMaster_Load(object sender, EventArgs e)
        {
            // get the current page...
            string pageSrc = GetPageSource();

            try
            {
                Hanhud.Web.UI.SitePage currentPage = (Hanhud.Web.UI.SitePage)Page.LoadControl(pageSrc);

                if (currentPage.Permission.SelectAccess)
                {
                    CurrentPage = currentPage;
                    CurrentPage.Header = Header;
                    CurrentPage.Footer = Footer;
                    CurrentPage.Navigator = Navigator;

                    // Get current page
                    CPageContext.Current.CurrentPage = CurrentPage;

                    // add the header control before the page rendering...
                    Header.Controls.Add(Navigator);
                    Controls.AddAt(0, Header);
                    //Controls.AddAt(1, Navigator);
                    // add the page before the page rendering...
                    Controls.Add(CurrentPage);
                    // add the footer control after the page...
                    Controls.Add(Footer);
                }
                else
                {
                    // Phat sinh permission exception, thong bao ko du tham quyen de truy cap vao tai nguyen nay
                    throw new System.UnauthorizedAccessException(Hanhud.Web.Resources.DException.DeniedSelect);
                }
            }
            catch (System.IO.FileNotFoundException)
            {
                // Phat sinh application exception, thong bao tai nguyen truy xuat khong ton tai hoac khong co tham quyen
                throw new ApplicationException(Hanhud.Web.Resources.HANHUD.ResourceNotFound);
            }
        }

        void HANHUDMaster_Unload(object sender, EventArgs e)
        {
            // make sure the HanhudContext is disposed of...
            Hanhud.Web.CPageContext.Current.Dispose();
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.WriteLine(
                @"<div class=""WidthPages"">");

            base.Render(writer);

            writer.WriteLine(
                @"
                </div>
            ");
        }

        protected virtual string GetPageSource()
        {
            string mod = string.IsNullOrEmpty(Request.QueryString["mod"]) ? string.Empty : Request.QueryString["mod"];
            string pag = string.IsNullOrEmpty(Request.QueryString["pag"]) ? "Home" : Request.QueryString["pag"];

            if (string.IsNullOrEmpty(mod))
                return string.Format("~/Pages/{0}.ascx", pag);
            else
                return string.Format("~/Pages/{0}/{1}.ascx", mod, pag);
        }

        protected static void CheckRequestValidity(System.Web.HttpRequest request)
        {
            // ip with 
            // deny access if POST request comes from other server
            if (request.HttpMethod == "POST" && request.UrlReferrer != null && request.Url.Host != null && request.UrlReferrer.Host != request.Url.Host)
            {
                Hanhud.Web.CLinkBuilder.AccessDenied();
            }
        }

        public string GetImageUrl(string imageUrl)
        {
            return GetImageUrl(imageUrl, false);
        }

        public string GetImageUrl(string imageUrl, bool useTheme)
        {
            if (useTheme)
            {
                if (imageUrl.IndexOf("~/") >= 0) imageUrl = imageUrl.Replace("~/", "");
                else if (imageUrl[0] == '/') imageUrl = imageUrl.Remove(0);

                return Page.ResolveUrl(string.Format("~/App_Themes/{0}/{1}", Config.CSiteConfig.Current.Theme, imageUrl));
            }
            else
                return Page.ResolveUrl(imageUrl);
        }

        public string GetPageUrl(string pageUrl)
        {
            string strBaseUrl = string.Empty; // CUrlBuilder.Path;

            if (pageUrl.IndexOf("~/") >= 0) pageUrl = pageUrl.Replace("~/", "");
            else if (pageUrl[0] == '/') pageUrl = pageUrl.Remove(0);

            //return string.Format("http://localhost{0}{1}", strBaseUrl, pageUrl);
            return string.Format("http://{2}{0}/{1}", Request.ApplicationPath, pageUrl, Request.Url.Host);
        }

        protected void RegisterCss(string href)
        {
            System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
            gridCss.Attributes["type"] = "text/css";
            gridCss.Attributes["rel"] = "Stylesheet";

            if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
            else if (href[0] == '/') href = href.Remove(0);

            gridCss.Href = string.Format("~/App_Themes/{0}/{1}", Config.CSiteConfig.Current.Theme, href);
            Page.Header.Controls.Add(gridCss);
        }

        protected void RegisterCss(string href, bool useTheme)
        {
            if (useTheme) RegisterCss(href);
            else
            {
                System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
                gridCss.Attributes["type"] = "text/css";
                gridCss.Attributes["rel"] = "Stylesheet";

                if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
                else if (href[0] == '/') href = href.Remove(0);

                gridCss.Href = string.Format("~/{0}", href);
                Page.Header.Controls.Add(gridCss);
            }
        }
    }
}
